package com.yunhe.merchants.service.impl;

import com.yunhe.common.constant.TimeConsts;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ModelNotFoundException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.model.ResultObject;
import com.yunhe.common.model.mybatis.PageResult;
import com.yunhe.common.util.StringUtil;
import com.yunhe.merchants.constant.MyProjectConsts;
import com.yunhe.merchants.domain.MyProject;
import com.yunhe.merchants.model.FilePath;
import com.yunhe.merchants.model.FilterCondition;
import com.yunhe.merchants.model.HousingMerchantsInfo;
import com.yunhe.merchants.model.SuccessProjectUpload;
import com.yunhe.merchants.service.ISuccessProjectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author: DongWenYu
 * @Date: 2021/5/7 21:22
 */
@Service
public class SuccessProjectServiceImpl extends MyProjectServiceImpl implements ISuccessProjectService {

    private static final Logger logger = LoggerFactory.getLogger(SuccessProjectServiceImpl.class);

    private List<String> status = new ArrayList<>();

    @PostConstruct
    private void init(){
        Collections.addAll(status,MyProjectConsts.COMPANY_STATUS.Success.value(),MyProjectConsts.COMPANY_STATUS.LeaveSoon.value());
    }

    @Override
    public PageResult selectByFilterCondition(FilterCondition filterCondition, Long userId, int page, int size) {
        return super.selectByFilterCondition(filterCondition,status,userId,page,size);
    }

    @Override
    public void leaveInMonth() throws ModelNotFoundException, ArgumentErrorException {
        List<MyProject> myProjects = myProjectRepository.selectLeaveInMonth();
        for (MyProject myProject : myProjects) {
            if (myProject.getExpireTime().getTime() - System.currentTimeMillis() < TimeConsts.month &&
            myProject.getExpireTime().getTime() > System.currentTimeMillis()) {
                if(myProject.getChosenOffice() != null){
                    authorityClient.setOfficeStatus(myProject.getId(),myProject.getChosenOffice(),myProject.getCompanyName(),"99");
                }
                myProject.setCompanyStatus(MyProjectConsts.COMPANY_STATUS.LeaveSoon.value());
                myProjectRepository.update(myProject);
                logger.info("成功项目即将离场,id:{}",myProject.getId());
            }
        }
    }

    @Override
    public List<MyProject> export(String ids, FilterCondition filterCondition) {
        return super.export(ids,filterCondition,status);
    }

    @Override
    public void upload(List<SuccessProjectUpload> successProjectUploads, Long userId , Long stationId) throws ModelNotFoundException, ArgumentErrorException {
        //upload转Do
        List<MyProject> myProjects = convertUploadToDo(successProjectUploads,userId , stationId);
        //批量插入
        myProjectRepository.insertBatch(myProjects);
        for (MyProject myProject : myProjects) {
            if(myProject.getChosenOffice() != null){
                ResponseEntity<ResultObject> responseEntity = authorityClient.setOfficeStatus(myProject.getId(), myProject.getChosenOffice(), myProject.getCompanyName(), "03");
                if(responseEntity.getStatusCode().is2xxSuccessful()){
                    Object results = responseEntity.getBody().getResults();
                    if(results != null){
                        if(results.toString().contains("error")){
                            myProjectRepository.delete(myProject.getId());
                            throw new ArgumentErrorException(results.toString().split("-")[1]);
                        }
                    }
                }
            }
        }
        logger.info("导入{}条数据进入数据库",myProjects.size());
    }

    @Override
    public void leave() throws ArgumentErrorException, ModelNotFoundException {
        List<MyProject> myProjects = myProjectRepository.selectLeave();
        for (MyProject myProject : myProjects) {
            if (myProject.getExpireTime().getTime() <= System.currentTimeMillis()){
                myProject.setCompanyStatus(MyProjectConsts.COMPANY_STATUS.Leave.value());
                myProjectRepository.update(myProject);
                authorityClient.setOfficeStatus(myProject.getId(),myProject.getChosenOffice(),myProject.getCompanyName(),"01");
            }
        }
    }

    @Override
    public HousingMerchantsInfo getMerchantsInfo(Long id) {
        HousingMerchantsInfo housingMerchantsInfo = myProjectRepository.getMerchantsInfo(id);
        if(housingMerchantsInfo != null){
            //文件地址转文件名
            if(!StringUtil.isEmpty(housingMerchantsInfo.getContract())){
                List<FilePath> filePaths = new ArrayList<>();
                String[] split = housingMerchantsInfo.getContract().split(",");
                String contractName = housingMerchantsInfo.getContractName();

                if(split.length >= 1){
                    for (int i = 0;i < split.length;i++) {
                        FilePath filePath = new FilePath();
                        filePath.setFilePath(split[i]);
                        if(!StringUtil.isEmpty(contractName)){
                            String[] names = contractName.split(",");
                            filePath.setFileName(names[i]);
                        }else {
                            String fileName = split[i].substring(split[i].lastIndexOf("/")+1,split[i].lastIndexOf("."));
                            filePath.setFileName(fileName);
                        }
                        filePaths.add(filePath);
                    }
                    housingMerchantsInfo.setContractFiles(filePaths);
                }
            }
        }
        return housingMerchantsInfo;
    }


}
